package com.sixth.volunteerservicesystem.Controller.ExamController.frontExam;

import com.sixth.volunteerservicesystem.Dao.QuestionRepository;
import com.sixth.volunteerservicesystem.domain.Subjects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Steve Jobs
 * @create 2020-12-16 10:49
 */
@Controller
public class Exam {

    @Autowired
    QuestionRepository questionRepository;

    @Resource
    private JdbcTemplate jdbcTemplate;


    @RequestMapping("exam")
    public String exam(Model model) {
        Subjects randomSubjects = null;
        Map<Integer, Subjects> map = new HashMap<>();

        Integer maxId = jdbcTemplate.queryForObject(String.format("SELECT MAX(subject_id) FROM Subjects"), Integer.class);

        int n = 0;
        for(int i = 0;i < 20;i++){
            n = (int) (Math.random() * maxId + 1);
            if(questionRepository.existsById(n)){
            randomSubjects = questionRepository.findById(n).get();
                if(!map.containsValue(randomSubjects)){
                    map.put(i + 1, randomSubjects);
                }else{
                    i--;
                }

            }else{
                i--;
            }
        }
        model.addAttribute("map",map);
        return "exam/exam";
    }
}
